package com.day1018;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class MainText {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read("src\\main\\java\\com\\day1018\\phone.xml");
        Element rootElement = document.getRootElement();
        System.out.println(rootElement.getName());
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            System.out.println("标签名称：" + element.getName());
            System.out.println("标签属性：" + element.attribute("name").getValue());
            List<Element> childs = element.elements();
            for (Element child : childs) {
                System.out.println("标签名字：" + child.getName());
                System.out.println("标签属性：" + child.attribute("name").getValue());
            }
        }
        Element brand = rootElement.addElement("Brand");
        brand.addAttribute("name","小米");
        Element type = brand.addElement("Type");
        type.addAttribute("name","mi10");
        //  写入文档
        FileWriter fileWriter = new FileWriter("src\\main\\java\\com\\day1018\\phone2.xml");
        OutputFormat outputFormat = new OutputFormat();
        XMLWriter xmlWriter = new XMLWriter(fileWriter,outputFormat);
        xmlWriter.write(document);
        fileWriter.close();
    }
}
